//
//  MyInfoViewController.m
//  YeDian
//
//  Created by 罗西 on 3/24/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "MyInfoViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"


@interface MyInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate>{
    NSData *data;
    NSDictionary *myInfoDic;
    int code;
    NSMutableArray *photoArray;
    NSInteger imgIndex;
}

@property (nonatomic,strong) UITableView *mainTableView;
@property (nonatomic,strong) UIButton *imgBtn;
@property (nonatomic,strong) NSString*  serverPath;
@property (nonatomic,strong) NSString *avatar;
@property (nonatomic,assign) BOOL isEditing;
@property (nonatomic,assign) BOOL isAvatar;
@property (nonatomic,strong) UIButton *btn;

@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"资料";
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    UIBarButtonItem *btnBar = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    [rightBtn addTarget:self action:@selector(editFn:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnBar;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //self.view.backgroundColor = [UIColor whiteColor];
    

    
    
    _isEditing = NO;
    photoArray = [NSMutableArray new];
    [self loadData];
}

-(void)editFn:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"编辑"]) {
        [sender setTitle:@"保存" forState:UIControlStateNormal];
        _isEditing = YES;
    }else{
        [sender setTitle:@"编辑" forState:UIControlStateNormal];
        [self doSaveOrderFn];
        _isEditing = NO;
    }
    [self.mainTableView reloadData];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)doSaveOrderFn{
    //kdType
    
    UITextField *tf1 = [self.view viewWithTag:101];
    UITextField *tf2 = [self.view viewWithTag:102];
    UITextField *tf3 = [self.view viewWithTag:103];
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSLog(@"str:%@",str);
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"index.php/AppUser/updateUserFn"];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    //
    [req addPostValue:tf3.text forKey:@"qm"];//快递类型
    [req addPostValue:tf1.text forKey:@"nickname"];
    NSLog(@"tf2.text:%@",tf2.text);
    if ([tf2.text isEqualToString:@"男"]) {
        [req addPostValue:@"1" forKey:@"gender"];
    }else{
        [req addPostValue:@"2" forKey:@"gender"];
    }
    
    
    if (self.serverPath.length != 0) {

        NSString* tmpImg=[NSString stringWithFormat:@"/upload/%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:tmpImg forKey:@"avatar"];
        
//        if (_isAvatar) {
//            NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
//            NSLog(@"tmpImg:%@",tmpImg);
//            [req addPostValue:tmpImg forKey:@"avatar"];
//        }else{
//            NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
//            NSLog(@"tmpImg:%@",tmpImg);
//            [req addPostValue:tmpImg forKey:@"avatar"];
//        }
    }

    
    
    
    
    
    
    NSString*  uid=[ud objectForKey:@"uid"];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",uid] forKey:@"uid"];
    [req startSynchronous];
    NSLog(@"req:%@",req);
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        NSDictionary* dic=[response JSONValue];
        code=[[dic objectForKey:@"code"] intValue];
        [self performSelectorOnMainThread:@selector(finishFn) withObject:nil waitUntilDone:YES];
    }
    
}

-(void)finishFn{
    if (code==1) {
        [self.view makeToast:@"保存资料成功" duration:1.0 position:@"center"];
        [self loadData];
        
    }else{
        [self.view makeToast:@"保存资料失败" duration:1.0 position:@"center"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    }
}

-(void)loadData{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"uid"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/AppUser/loadUserInfo?uid="];
    loginURL=[loginURL stringByAppendingFormat:@"%@",mp_];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req startSynchronous];
    NSError *error = [req error];
    
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        [self loadFooter];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}

-(void)loadFooter{
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"uid"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"index.php/UserImg/findUserImgList?uid="];
    loginURL=[loginURL stringByAppendingFormat:@"%@",mp_];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req startSynchronous];
    NSError *error = [req error];
    
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        
        photoArray = [[NSMutableArray alloc]initWithArray:[response JSONValue]];
        
        [self.mainTableView reloadData];
        
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                                   initWithTarget:self
                                                   action:@selector(myHandleTableviewCellLongPressed:)];
        
        longPress.delegate = self;
        longPress.minimumPressDuration = 0.8;
        [self.mainTableView addGestureRecognizer:longPress];
        
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}

#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (photoArray.count>5) {
        return 5+5;
    }
    return 5+photoArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
//    if (section == 4) {
//        if (photoArray.count>5) {
//            return 5*(SCREEN_WIDTH-40+20);
//        }
//        return photoArray.count*(SCREEN_WIDTH-40+20);
//    }
    return 10;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    if (section == 4) {
//        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, photoArray.count*(SCREEN_WIDTH-40+20))];
//        int y = 0;
//        for (long i = photoArray.count-1; i > -1&&(i > photoArray.count - 6); i--) {
//            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20+(SCREEN_WIDTH-40+20)*y, SCREEN_WIDTH-40, (SCREEN_WIDTH-40))];
//            btn.layer.borderColor = [UIColor redColor].CGColor;
//            btn.layer.borderWidth = 3.0f;
//            NSDictionary *dic = [photoArray objectAtIndex:i];
//            NSString *strUrl = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"img_path"]];
//            NSLog(@"strURL:%@",strUrl);
//            [btn sd_setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
//            //[btn setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];
//            //btn.backgroundColor = [UIColor lightGrayColor];
//            [view addSubview:btn];
//            y++;
//
//        }
//        
//        return view;
//    }
    
    return nil;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 4){
        return 44;
    }else if (indexPath.section > 4){
        return SCREEN_WIDTH-40;
    }
    return 44;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell new];
    
    NSArray *array = @[@"头像",@"昵称",@"性别",@"签名",@"我的照片"];
    NSArray *array2 = @[@"请输入昵称",@"请选择性别",@"请输入签名"];
    UILabel *TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, 30, 12)];
    if (indexPath.section == 4) {
        TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, 80, 12)];
    }else if (indexPath.section == 0){
        TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, 80, 20)];
    }
    if(indexPath.section != 4 && indexPath.section<5){
        TitleLabel.center = CGPointMake(TitleLabel.center.x, cell.center.y);
        TitleLabel.text = [array objectAtIndex:indexPath.section];
        TitleLabel.font = [UIFont systemFontOfSize:13];
        
    }
    [cell addSubview:TitleLabel];
    
    if (indexPath.section == 0) {
        _imgBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, 10, 60, 60)];
        NSString *strUrl;
        NSLog(@"strUrl:%@",strUrl);
        if ((![[myInfoDic objectForKey:@"avatar"] isEqual:[NSNull null]])&&[[myInfoDic objectForKey:@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
            strUrl = [NSString stringWithFormat:@"%@",[myInfoDic objectForKey:@"avatar"]];
        }else{
            strUrl = [NSString stringWithFormat:@"%@%@",HOST,[myInfoDic objectForKey:@"avatar"]];
        }
        NSLog(@"strUrl:%@",strUrl);
        [_imgBtn setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"add_pic.png"]];
        //[_imgBtn setImage:[UIImage imageNamed:@"add_pic.png"] forState:UIControlStateNormal];
        [cell addSubview:_imgBtn];
        [_imgBtn addTarget:self action:@selector(paiZhaoFn2) forControlEvents:UIControlEventTouchUpInside];
        _imgBtn.userInteractionEnabled = _isEditing;
    }else if (indexPath.section == 1 ||indexPath.section == 2||indexPath.section == 3){
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(80, 5, 200, 34)];
        tf.placeholder = [array2 objectAtIndex:indexPath.section-1];
        [cell addSubview:tf];
        tf.font = [UIFont systemFontOfSize:13];
        tf.userInteractionEnabled = _isEditing;
        if (_isEditing) {
            tf.layer.borderColor = [UIColor lightGrayColor].CGColor;
            tf.layer.borderWidth = 1.0f;
        }else{
            tf.layer.borderColor = [UIColor clearColor].CGColor;
            
        }
        
        if(indexPath.section == 1){
            tf.text = [myInfoDic objectForKey:@"nickname"];
        }else if (indexPath.section == 2){
            tf.text = [[myInfoDic objectForKey:@"gender"]intValue] == 1?@"男":@"女";
        }else if (indexPath.section == 3){
            NSString *str = [[myInfoDic objectForKey:@"qm"]isEqual:[NSNull null]]?@"":[myInfoDic objectForKey:@"qm"];
            tf.text = str;
        }
        
        tf.tag = 100+indexPath.section;
    }else if (indexPath.section == 4){
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2, 10, 55, 24)];
        btn.layer.borderColor = [UIColor orangeColor].CGColor;
        btn.layer.borderWidth = 1.0f;
        [btn setTitle:@"添加" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:11];
        btn.layer.cornerRadius = 12;
        [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [cell addSubview:btn];
        [btn addTarget:self action:@selector(addPhoto) forControlEvents:UIControlEventTouchUpInside];
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ce"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ce"];
        }
        UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH-40, (SCREEN_WIDTH-40))];
        btn2.layer.borderColor = [UIColor redColor].CGColor;
        btn2.layer.borderWidth = 3.0f;
        NSDictionary *dic = [photoArray objectAtIndex:indexPath.section-5];
        NSString *strUrl = [NSString stringWithFormat:@"%@%@",HOST,[dic objectForKey:@"img_path"]];
        NSLog(@"section:%ld  strURL:%@",(long)indexPath.section,strUrl);
        [btn2 sd_setImageWithURL:[NSURL URLWithString:strUrl] forState:UIControlStateNormal placeholderImage:[UIImage new]];

        if (indexPath.section == 5) {
            UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]]];
            [cell.imageView setImage:image];
        }else{
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage new]];
        }
        
        return cell;
    }
    
    return cell;
}

-(void)paiZhaoFn2{
    _isAvatar = YES;
    [self paiZhaoFn];
}

-(void)addPhoto{
    _isAvatar = NO;
    [self paiZhaoFn];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section >=5) {
        NSLog(@"ffff");
        
        imgIndex = indexPath.section - 5;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定删除照片吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.delegate = self;
        // optional - add more buttons:
        [alert show];
    }
}

-(void)paiZhaoFn{
    
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
        
    }else{
        // [[NSNotificationCenter defaultCenter] postNotificationName:@"paidanFn" object:nil];
        
        
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
    }
    
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (buttonIndex) {
        case 0://Take picture
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
            }else{
                NSLog(@"模拟器无法打开相机");
            }
            [self presentModalViewController:picker animated:YES];
            break;
            
        case 1://From album
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentModalViewController:picker animated:YES];
            break;
            
        default:
            //[self dismissModalViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
            break;
    }
}

#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CGSize newSize=CGSizeMake(160, 160);
        if (_isAvatar) {
            image=[self smallImg:image scaledToSize:newSize];
        }else{
            newSize=CGSizeMake(SCREEN_WIDTH-40, SCREEN_WIDTH-40);
            image=[self smallImg:image scaledToSize:newSize];
        }
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.jpg"];
        NSLog(@"filePath:%@",filePath);
        if (_isAvatar) {
            
            [_imgBtn setImage:image forState:UIControlStateNormal];
        }else{
            //[photoArray addObject:filePath];
        }
        
        self.avatar=filePath;
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //[picker dismissModalViewControllerAnimated:YES];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
        
        [self savePhotoFn];
        
    }
}

-(void)savePhotoFn{
    //NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString* uploadURL=@"yw_uploadify.php";
    uploadURL=[HOST stringByAppendingString:uploadURL];
    
    //NSLog(@"uploadURL=%@",uploadURL);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:uploadURL]];
    
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString* dateString = [fmt stringFromDate:now];
    NSLog(@"%@", dateString);
    
    
    self.serverPath=[Tools md5:dateString];
    
    
    
    
    [request setPostValue:[NSString stringWithFormat:@"%@",self.serverPath] forKey:@"serverImgName"];
    
    NSLog(@".....serverPath=%@", self.serverPath);
    
    self.serverPath=[self.serverPath stringByAppendingString:@".jpg"];
    
    [request setFile:self.avatar  forKey:@"filename"];
    
    
    
    //[request setValue:uid forKey:@"uid"];
    request.delegate = self;
    //
//    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"正在处理中，请稍后..."];
    
    
    
    
    [request startAsynchronous];
    
    
    [self savrMyAvatarFn];
}

- (void) myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"UIGestureRecognizerStateBegan");
        
        CGPoint point = [gestureRecognizer locationInView:self.mainTableView];
        NSIndexPath * indexPath = [self.mainTableView indexPathForRowAtPoint:point];
        if (indexPath.section >=5) {
            NSLog(@"ffff");
            
            imgIndex = indexPath.section - 5;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定删除照片吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate = self;
            // optional - add more buttons:
            [alert show];
        }
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        NSLog(@"UIGestureRecognizerStateChanged");
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        NSLog(@"UIGestureRecognizerStateEnded");
    }
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString* mp_ = [accountDefaults objectForKey:@"uid"];
        //NSString* mp_=[ud objectForKey:@"mp"];
        if (!mp_) {
            return;
        }
        NSLog(@"mp:%@",mp_);
        NSDictionary *dic = [photoArray objectAtIndex:imgIndex];
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"/index.php/UserImg/delPhotoServerFn?img_path="];
        loginURL=[loginURL stringByAppendingFormat:@"%@",[dic objectForKey:@"img_path"] ];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        [req addPostValue:mp_ forKey:@"uid"];
        [req startSynchronous];
        NSError *error = [req error];
        
        
        if (!error) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [MBProgressHUD hideHUDForView:app.window animated:YES];
            
            NSString *response = [req responseString];
            NSLog(@"保存返回结果%@",response);
            myInfoDic=[response JSONValue];
            NSString* uid=[myInfoDic objectForKey:@"uid"];
            NSLog(@"ID%@",uid);
            
            [self loadData];
            //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
        }else{
            NSLog(@"move failed:%@", [error localizedDescription]);
        }
    }
}

-(void)savrMyAvatarFn{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uid=[userDefaults objectForKey:@"uid"];
    NSString* strFlag=[userDefaults objectForKey:@"flag"];
    int flag=[strFlag intValue];
    
    [self.view makeToast:@"照片保存成功!"
                duration:1.0
                position:[NSValue valueWithCGPoint:CGPointMake(160, 210)]
     ];
    //NSDictionary* dic=[NSDictionary dictionaryWithObject:self.avatar forKey:@"avatar"];
    
    
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [MBProgressHUD hideHUDForView:app.window animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    
    if(!_isAvatar){
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString* mp_ = [accountDefaults objectForKey:@"phone"];
        //NSString* mp_=[ud objectForKey:@"mp"];
        if (!mp_) {
            return;
        }
        NSLog(@"mp:%@",mp_);
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"index.php/UserImg/saveImg"];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        NSString*  uid2=[ud objectForKey:@"uid"];
        
        [req addPostValue:[NSString stringWithFormat:@"%@",uid2] forKey:@"uid"];
        
        NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:[NSString stringWithFormat:@"/upload/%@",tmpImg] forKey:@"img_path"];
        
        [req startSynchronous];
        NSError *error = [req error];
        
        
        if (!error) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [MBProgressHUD hideHUDForView:app.window animated:YES];
            
            NSString *response = [req responseString];
            NSLog(@"保存返回结果%@",response);
            myInfoDic=[response JSONValue];
            NSString* uid=[myInfoDic objectForKey:@"uid"];
            NSLog(@"ID%@",uid);
            
            
            //[self.mainTableView reloadData];
            [self.mainTableView removeFromSuperview];
            self.mainTableView = nil;
            [self loadData];
            
            self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
            [self.view addSubview:self.mainTableView];
            [self.mainTableView setDataSource:self];
            [self.mainTableView setDelegate:self];
            [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
            [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
            [self.view addSubview:self.mainTableView];
            //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
        }else{
            NSLog(@"move failed:%@", [error localizedDescription]);
        }
    }
    
    
}



-(UIImage*)smallImg:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
